﻿''
'' sLotShuffle - A SlotMusic Helper Aplication
'' 
'' Copyright ©  2009 Chromableed Studios
''  Dillon Graham
''  chromableedstudios ( a.t ) gmail (dot) com
''  Addison Hudzik
''  Addison.Hudzik ( a.t ) gmail (dot) com
''
''  This program is free software: you can redistribute it and/or modify
'' it under the terms of the GNU General Public License as published by
''the Free Software Foundation, either version 3 of the License, or
''(at your option) any later version.
''
''   This program is distributed in the hope that it will be useful,
''  but WITHOUT ANY WARRANTY; without even the implied warranty of
''  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
''GNU General Public License for more details.
''
''  You should have received a copy of the GNU General Public License
''along with this program.  If not, see <http://www.gnu.org/licenses/>.
''
''
''Import the namespaces
Imports System
Imports System.IO
Imports System.Collections

Public Class MainSlotShuffleForm
    ''best practices?
    ''working code.
    ''
    ''anyhoo...


    '' Code Block borrowed/modified from:
    ''http://social.msdn.microsoft.com/forums/en-US/Vsexpressvb/thread/66037390-788f-4f25-a276-458784ab9d56/
    '' Thanks!
    ''
    ''Shuffles the items in the list box
    Private Sub ShuffleItems(ByVal Listbox1 As System.Windows.Forms.ListBox)

        Dim Random As New System.Random

        Listbox1.BeginUpdate()

        Dim ArrayList As New System.Collections.ArrayList(Listbox1.Items)

        Listbox1.Items.Clear()

        While ArrayList.Count > 0

            Dim Index As System.Int32 = Random.Next(0, ArrayList.Count)

            Listbox1.Items.Add(ArrayList(Index))

            ArrayList.RemoveAt(Index)

        End While

        Listbox1.EndUpdate()

    End Sub




    ''borrowed/modified from:
    '' http://dotnetdud.blogspot.com/2007/06/selecting-folder-in-vbnet.html
    ''
    ''Creates a select a folder dialog
    Private Sub BtnFolder_Click()

        Dim MyFolderBrowser As New System.Windows.Forms.FolderBrowserDialog

        ' Descriptive text displayed above the tree view control in the dialog box
        MyFolderBrowser.Description = "Select the Folder to shuffle or "

        ' Sets the root folder where the browsing starts from
        'MyFolderBrowser.RootFolder = Environment.SpecialFolder.MyDocuments

        ' Do not show the button for new folder
        MyFolderBrowser.ShowNewFolderButton = False

        Dim dlgResult As DialogResult = MyFolderBrowser.ShowDialog()

        If dlgResult = Windows.Forms.DialogResult.OK Then
            WorkingDirectory = MyFolderBrowser.SelectedPath
        End If

    End Sub




    Dim WorkingDirectory As String


    Private Sub ShuffleButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShuffleButton.Click
        ''DO THE TWIST
        ShuffleItems(ListBox1)
        ''Allow saving after the listbox has been filled/shuffled
        SaveButton.Enabled = True
    End Sub



    Friend IsItImported As Boolean
    ''
    ''Clears the listbox and populates it with music from the selected directory
    Sub PopulateListBox()
        Try
            ''1st version for standard(not importing) listbox fill
            If IsItImported = False Then
                Me.ListBox1.Items.Clear()
                For Each foundSong As String In _
            My.Computer.FileSystem.GetFiles( _
            WorkingDirectory, _
            FileIO.SearchOption.SearchTopLevelOnly, "*.mp3", "*.wma")

                    Me.ListBox1.Items.Add(foundSong)
                Next

            ElseIf IsItImported = True Then
                ''2nd version for import from m3u listbox fill (difference is folder select dialog)
                ''Clears the listbox and populates it with music from the selected directory for playlist
                Me.ListBox1.Items.Clear()
                For Each foundSong As String In _
            My.Computer.FileSystem.GetFiles( _
            CopyingWorkingDirectory2, _
            FileIO.SearchOption.SearchTopLevelOnly, "*.mp3", "*.wma")

                    Me.ListBox1.Items.Add(foundSong)
                Next
            End If
        Catch
        End Try
    End Sub

    Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadButton.Click
        ''Run a sub to select a folder and populate the list box from its music
        DoTheLoading()
    End Sub

    ''load a folder and populate the list then enable shuffle
    Sub DoTheLoading()
        Try
            BtnFolder_Click()
            IsItImported = False
            PopulateListBox()
            ShuffleButton.Enabled = True

        Catch
            MessageBox.Show("error")
        End Try
    End Sub
    ''load a pre-selected folder and populate the list then enable shuffle (m3u import file directory)
    Sub DoTheLoadingImport()
        Try
            IsItImported = True
            PopulateListBox()
            ShuffleButton.Enabled = True

        Catch
            MessageBox.Show("error")
        End Try
    End Sub

    ''Function to check if a file has been previously shuffled (ie 0x0 added)
    ''
    ''Returns: either the original string, or the string with 0x0 removed
    Function FullyTestedName() As String

        If HasItBeenPrevShuffledBySS() = True Then
            ''The file has been found to be previously shuffled
            ''
            ''declare the string to lose the numbers from
            Dim LoseTheNum As String = ShortWorkingName
            ''set up an array with the 0x0 and numbers (ie the set to be removed)
            Dim MyChar As Char() = {"0"c, "x"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c}
            ''do the actual removal of characters from the start of the string
            Dim NewString As String = LoseTheNum.TrimStart(MyChar)

            Return NewString

        Else
            ''the file has not been previously shuffled -return original string
            Return ShortWorkingName
        End If

    End Function
    Friend PrevShuffled As Boolean

    Function HasItBeenPrevShuffledBySS() As Boolean

        ''Check if previously shuffled by 'sLotShuffle with 0x0
        If ShortWorkingName.StartsWith("0x0") Then
            PrevShuffled = True
            Return True
        Else
            Return False
        End If

    End Function
    ''declare Vars for the rename
    Friend ShortWorkingName, FullFileDirandName, NewlyAppendedName, WorkingName As String

    ''this sub does the actual rename
    Sub renametest()
        Try
            ''set up the counter for the shuffle order
            Dim Append As Integer
            Append = 0
            ''create a loop from the listbox items
            For Thisloop As Integer = 0 To ListBox1.Items.Count - 1

                ''apply a value for this iteration of the loop
                FullFileDirandName = ListBox1.Items(Thisloop)
                WorkingName = ListBox1.Items(Thisloop)

                ''Create a getinfo to help parse filename
                Dim TheGetFileInfoObject As System.IO.FileInfo

                TheGetFileInfoObject = My.Computer.FileSystem.GetFileInfo(FullFileDirandName)

                ''Seperate the Path From the Name and Save as var

                ShortWorkingName = TheGetFileInfoObject.Name

                If PrevShuffled Then
                    ''Create a name with a number in front for this loop
                    NewlyAppendedName = "0x0" & Append & FullyTestedName()
                Else
                    ''Create a name with a number in front for this loop
                    NewlyAppendedName = "0x0" & Append & " " & FullyTestedName()
                End If

                ''Actually do the Rename of the files for shuffle
                My.Computer.FileSystem.RenameFile(FullFileDirandName, NewlyAppendedName)
                ''increment the counter for the loop
                Append = Append + 1
            Next
        Catch
            MessageBox.Show("Error: check file names and playist contents--a file may be missing that is on the playlist. If you have already saved the playlist you may also see this error.")
        End Try
        MessageBox.Show("Complete!")
    End Sub

    Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
        ''go to the sub that performs the name change
        ''then clear and repopulate the list
        renametest()
        IsItImported = False
        PopulateListBox()

    End Sub


    ''end of shuffle and tested code
    ''begin m3u support code
    ''declare vars

    Friend m3uFileandLocation, RelativePathAppended, ToTestForRelativePath As String
    Sub ImportM3UList()
        Try
            Dim openFileDialog1 As New OpenFileDialog

            openFileDialog1.InitialDirectory = System.Environment.CurrentDirectory
            openFileDialog1.Title = "Open .m3u Playlist"
            openFileDialog1.Filter = "M3U Playlist (*.m3u)|*.m3u"
            openFileDialog1.FilterIndex = 1
            openFileDialog1.RestoreDirectory = True

            If openFileDialog1.ShowDialog() = DialogResult.OK Then
                m3uFileandLocation = openFileDialog1.FileName
            End If

            ''this throws an error if you choose cancel(?)

            Dim objReader As New StreamReader(m3uFileandLocation)
            Dim sLine As String = ""
            Dim arrText As New ArrayList()

            Do
                sLine = objReader.ReadLine()
                If Not sLine Is Nothing Then

                    If sLine.StartsWith("#") Then
                        ''nothing?
                    ElseIf sLine = ("") Then
                        ''nothing?
                    Else

                        ToTestForRelativePath = sLine
                        CheckForRelPath()
                        If CheckForRelPath() = True Then
                            ''todo:test if item exists before you add it

                            ListBox1.Items.Add(sLine)
                        ElseIf CheckForRelPath() = False Then

                            Dim ImportFilem3uObject As System.IO.FileInfo
                            ImportFilem3uObject = My.Computer.FileSystem.GetFileInfo(m3uFileandLocation)

                            ''create vars for converting from relative to absolute
                            ''(by way of (m3u fullpath)-(m3u name)+(mp3 name from m3u)
                            Dim LongM3uName As String = ImportFilem3uObject.FullName
                            Dim ShortM3uName As String = ImportFilem3uObject.Name

                            ''Try for errors
                            Try
                                ''Create an appended(absolute) path for this instance 
                                ''of the loop
                                '' by splitting m3u file and location and adding
                                '' the path to the string(song name and relative path)  
                                RelativePathAppended = StrIDel(LongM3uName, ShortM3uName) & sLine

                            Catch
                                ''look for null string error
                                MessageBox.Show("Error in m3u relative path or no file present")
                            End Try

                            ''todo:insert test for does file exist and fail (dont add)
                            ''
                            ''^^ must have been late...

                            ''Add the FullyAppended (path and name) of each
                            ''loop instance for a song
                            ListBox1.Items.Add(RelativePathAppended)

                        End If

                    End If

                End If
            Loop Until sLine Is Nothing
            objReader.Close()

        Catch
        End Try
    End Sub

    ''test code to delete a substring 
    ''code block borrowed/modified from:
    ''http://vbcity.com/page.asp?f=howto&p=strings_strdel
    '*----------------------------------------------------------*
    '* Name       : StrIDel                                     *
    '*----------------------------------------------------------*
    '* Purpose    : Deletes a substring with a string.          *
    '*            : Case insensitive                            *
    '*----------------------------------------------------------*
    '* Parameters : TempStr Required. String to delete from.    *
    '*            : SubStr  Required. Substring to remove.      *
    '*----------------------------------------------------------*
    '* Returns    : The changed string                          *
    '*----------------------------------------------------------*
    Public Function StrIDel(ByVal TempStr As String, _
                            ByVal SubStr As String) As String


        Dim Dest As Long, Src As Long

        Dest = InStr(UCase$(TempStr), UCase$(SubStr))

        If Dest = 0 Then
            StrIDel = ""
            Exit Function
        End If

        Src = Dest + Len(SubStr)
        Mid(TempStr, Dest) = Mid(TempStr, Src)
        TempStr = Microsoft.VisualBasic.Left$(TempStr, Len(TempStr) - Len(SubStr))

        StrIDel = TempStr


    End Function


    Function CheckForRelPath() As Boolean
        Dim rrrPath As String = ToTestForRelativePath

        Return Path.IsPathRooted(rrrPath)
    End Function
    Friend CopyingWorkingDirectory, CopyingWorkingDirectory2

    Sub TESTM3UCODE()
        Dim ShouldItCopyM3UFiles As DialogResult

        ShouldItCopyM3UFiles = MessageBox.Show("Would you like to copy the playlist to a new folder?", "Import m3u Dialog", MessageBoxButtons.YesNo)

        If ShouldItCopyM3UFiles = System.Windows.Forms.DialogResult.Yes Then

            ' This is where the copy files to new folder loop should appear

            MessageBox.Show("If you want the songs on the playlist to play in order you must select save after the .m3u has been imported.")

            ''display a select folder dialog
            Dim CopyingFolderBrowser As New System.Windows.Forms.FolderBrowserDialog
            ' Descriptive text displayed above the tree view control in the dialog box
            CopyingFolderBrowser.Description = "Select the Folder to copy playlist songs to. (This will be on the MicroSD card, make a new folder if you need)"

            CopyingFolderBrowser.ShowNewFolderButton = True

            Dim copyingdlgResult As DialogResult = CopyingFolderBrowser.ShowDialog()


            If copyingdlgResult = Windows.Forms.DialogResult.OK Then
                CopyingWorkingDirectory = CopyingFolderBrowser.SelectedPath
                ''save the folder dialog result in order to populate the listbox later
                CopyingWorkingDirectory2 = CopyingFolderBrowser.SelectedPath

            End If

            ''populate listbox with songtitles and path
            ImportM3UList()

            ''loop through list in order to copy files onto microsd card
            For CopyingIndex As Integer = 0 To ListBox1.Items.Count - 1

                ''create a new file path and name

                ''create a fileinfoobject to seperatepath and name

                ''Create a getinfo to help parse filename
                Dim TheM3UGetFileInfoObject As System.IO.FileInfo

                TheM3UGetFileInfoObject = My.Computer.FileSystem.GetFileInfo(ListBox1.Items(CopyingIndex))


                ''Seperate the Path From the Name and Save as var


                Dim M3UNewFileLocation As String = CopyingWorkingDirectory & "\" & TheM3UGetFileInfoObject.Name

                Try
                    File.Copy(ListBox1.Items(CopyingIndex), M3UNewFileLocation)
                Catch
                End Try
            Next
            ''clears list box of working titles and replaces with moved files if importing and copying
            ListBox1.Items.Clear()


            DoTheLoadingImport()


        Else
            MessageBox.Show("You picked the .M3U Playlist and music files are already on the microSD card--If this is wrong, select cancel in the next window. For the M3U Playlist to play in order, press save after list is loaded.")

            ''Run the Import M3U Sub
            ImportM3UList()

        End If



    End Sub


    ''end of m3u test code

    Private Sub AboutButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutButton.Click
        DisplayAboutTheProg()
    End Sub


    Private Sub ImportM3Ubutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImportM3Ubutton.Click
        ''after button press clear the listbox, enable buttons for save, move to
        ''importing m3u importing copy/not code
        ListBox1.Items.Clear()
        ShuffleButton.Enabled = True
        SaveButton.Enabled = True
        TESTM3UCODE()
    End Sub



    Private Sub CheckForUpdate()
        UpdateCheck.Show()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ''So long and thanks for all the fish!
        Me.Close()
    End Sub
    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        DisplayAboutTheProg()
    End Sub
    Private Sub DisplayAboutTheProg()
        MessageBox.Show("This Program is (c)2009 Chromableed Studios" + vbCrLf + "  Dillon Graham, Addison Hudzik " + vbCrLf + vbCrLf + "'sLot Shuffle is provided as is for free and without any warranty under the terms of the GNU GPLv3 see: <http://www.gnu.org/licenses/>." + vbCrLf + vbCrLf + " 'sLot Shuffle 1.5 is a release candidate version which means some bugs may still be present, although it has been well tested." + vbCrLf + "If you find a bug, have any questions or want to say thanks please contact chromableedstudios ( a.t ) gmail (dot) com ")
    End Sub

    Private Sub CheckForuToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckForuToolStripMenuItem.Click
        CheckForUpdate()
    End Sub
    Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
        ''So long and thanks for all the fish!
        Me.Close()


    End Sub
    Private Sub ExitToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub
End Class
